package com.sunshine.student_register.ui.fragment.register;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.sunshine.student_register.database.StudentRegisterRepository;
import com.sunshine.student_register.database.register.RegisterEntity;
import com.sunshine.student_register.database.student.StudentEntity;

/**
 * @author sunshine
 * @date 2020/5/30
 * 签到活动的viewModel类，用于调控非界面的数据处理
 */
public class RegisterViewModel extends AndroidViewModel {

    private SharedPreferences sp;
    private StudentRegisterRepository repository;
    private int userId;
    private StudentEntity studentEntity;

    public RegisterViewModel(@NonNull Application application) {
        super(application);

        sp = getApplication().getSharedPreferences("app_setting", Context.MODE_PRIVATE);
        repository = new StudentRegisterRepository(getApplication());
    }

    /**
     * 登录方法
     * 如果上次登录过则自动登录
     * 如果没有则需要手动登录或注册
     * @return 是否已经登录
     */
    boolean hasLogin(){
        userId = sp.getInt("user_id", -1);
        studentEntity = repository.getStudent(userId);
        return -1 != userId && null != studentEntity;
    }

    StudentEntity getStudentEntity() {
        return studentEntity;
    }

    void toRegister(RegisterEntity registerEntity){
        repository.insertRegister(registerEntity);
    }
}
